<?php

namespace seecms\wechat\controller;

use seecms\db\SeeDbException;
use seecms\lib\response\JsonResponse;
use seecms\See;
use seecms\wechat\provider\UserLogin;
use seecms\wechat\lib\WechatOfficialAccount;

class User extends \seecms\controller\User
{
    /**
     * 微信登录
     * @return string
     * @throws \seecms\SeeException
     */
    public function login(): string
    {
        $type = See::request()->param('type') ?: 1;

        $data = $this->init();

        if ($type == UserLogin::TYPE_SCAN_WX) {
            try {
                $qrcode = WechatOfficialAccount::app()->qrcode;
                // 设置登录标识
                $flag = 'login_' . md5(uniqid());
                $result = $qrcode->temporary($flag, 600);
                $data['wx_qrcode'] = $qrcode->url($result['ticket']);
                $data['wx_flag'] = $flag;
            } catch (SeeDbException $exception) {

            }
        }

        return See::view()->fetch('user/login', $data);
    }

    /**
     * 微信扫码登录
     * @return JsonResponse
     */
    public function wxScan()
    {
        $flag = See::request()->post('flag') ?: '';

        // 获取缓存的值
        $data = See::cache()->get($flag);
        if ($data) {
            $user_login = See::provider()->user_login;
            $data['type'] = UserLogin::TYPE_SCAN_WX;
            $result = $user_login->doLogin($data);
            return JsonResponse::result($result);
        }

        return JsonResponse::success(2);
    }
}